﻿namespace WebPacker.Helpers
{
	using System;
	using System.Security.Cryptography;
	using System.Text;

	internal static class HashHelper
	{
		public static string ComputeMd5HashString(string value)
		{
			return ComputeMd5HashString(value, Encoding.UTF8);
		}

		public static string ComputeMd5HashString(string value, Encoding encoding)
		{
			if (string.IsNullOrEmpty(value))
			{
				return string.Empty;
			}

			if (encoding == null)
			{
				throw new ArgumentNullException("encoding");
			}

			byte[] hash;

			using (var md5 = MD5.Create())
			{
				hash = md5.ComputeHash(encoding.GetBytes(value));
			}

			return ToString(hash);
		}

		public static string ToString(byte[] value)
		{
			if (value == null)
			{
				throw new ArgumentNullException();
			}

			var chars = new char[value.Length * 2];
			var index = 0;

			for (var i = 0; i < chars.Length; i += 2)
			{
				byte item = value[index++];
				chars[i] = GetHexValue(item / 0x10);
				chars[i + 1] = GetHexValue(item % 0x10);
			}

			return new string(chars);
		}

		private static char GetHexValue(int i)
		{
			if (i < 10)
			{
				return (char)(i + 0x30);
			}

			return (char)((i - 10) + 0x61);
		}
	}
}
